#include <TimerOne.h>

const int pin = 9;
volatile int state = 0;


void setup() {
  Serial.begin(115200);
  pinMode(pin, OUTPUT);
//  pinMode(2, OUTPUT);
  Timer1.initialize(1000L*1000L);
  Timer1.pwm(9, 10);

  // attachInterrupt() only works on pin 2,3 for nano
  attachInterrupt(digitalPinToInterrupt(pin), toggle_pin3, CHANGE);
}


void toggle_pin3() {
  state = !state;
  digitalWrite(3, state);
}


String inStr = "";
void loop() {
  inStr = "";
  while (Serial.available() > 0) {
    int inChar = Serial.read();
    if ('\n' == inChar) {
      int duty = inStr.toInt();
      Serial.print("got: "); Serial.println(inStr);
      Serial.print("converted: "); Serial.println(duty);
      Timer1.setPwmDuty(pin, duty);
    }
    inStr += (char)inChar;
  }

  delay(1000);
}
